<template>
  <div class="store-detail-container">
    <div class="store-header" v-loading="storeLoading">
      <div class="store-info" v-if="store">
        <div class="store-image">
          <img :src="store.storepicture || require('@/assets/shop-cover.jpg')" :alt="store.storename">
        </div>
        <div class="store-details">
          <h1 class="store-name">{{ store.storename }}</h1>
          <p class="store-description">{{ store.storedescribe || '暂无描述' }}</p>
          <div class="store-actions" v-if="isStoreOwner">
            <el-button type="primary" @click="editStore">编辑商店信息</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="store-content">
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="菜品列表" name="dishes">
          <div class="dishes-section" v-loading="dishesLoading">
            <div class="dishes-header">
              <h3>菜品列表</h3>
              <el-button 
                type="primary" 
                @click="addDish" 
                v-if="isStoreOwner"
              >
                添加菜品
              </el-button>
            </div>
            
            <el-row :gutter="20">
              <el-col 
                :xs="24" 
                :sm="12" 
                :md="8" 
                :lg="6" 
                v-for="dish in dishes" 
                :key="dish.dishid"
              >
                <el-card class="dish-card" shadow="hover">
                  <div class="dish-image">
                    <img :src="dish.dishcover || require('@/assets/dishes/dish1.jpg')" :alt="dish.dishname">
                  </div>
                  <div class="dish-info">
                    <h4 class="dish-name">{{ dish.dishname }}</h4>
                    <p class="dish-description">{{ dish.dishdescribe || '暂无描述' }}</p>
                    <div class="dish-price">¥{{ dish.dishprice }}</div>
                    <div class="dish-actions">
                      <el-button 
                        type="success" 
                        size="small" 
                        @click="addToCart(dish)"
                        v-if="isLoggedIn && !isStoreOwner"
                      >
                        加入购物车
                      </el-button>
                      <div v-if="isStoreOwner" class="owner-actions">
                        <el-button 
                          type="primary" 
                          size="small" 
                          @click="editDish(dish)"
                        >
                          编辑
                        </el-button>
                        <el-button 
                          type="danger" 
                          size="small" 
                          @click="deleteDish(dish.dishid)"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <div class="no-dishes" v-if="!dishesLoading && dishes.length === 0">
              <div class="empty-state">
                <i class="el-icon-folder-opened empty-icon"></i>
                <p class="empty-text">暂无菜品</p>
                <p class="empty-subtext">店主还没有添加菜品</p>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="评论" name="comments">
          <div class="comments-section" v-loading="commentsLoading">
            <div class="comments-header">
              <h3>用户评论</h3>
              <el-button 
                type="primary" 
                @click="showCommentDialog = true"
                v-if="isLoggedIn"
              >
                发表评论
              </el-button>
            </div>
            
            <div class="comments-list">
              <div 
                v-for="comment in comments" 
                :key="comment.commentid"
                class="comment-item"
              >
                <div class="comment-header">
                  <span class="comment-user">用户</span>
                  <span class="comment-time">{{ formatTime(comment.commentid) }}</span>
                </div>
                <div class="comment-content">{{ comment.commentcontent }}</div>
                <div class="comment-actions" v-if="canEditComment(comment)">
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="editComment(comment)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="deleteComment(comment.commentid)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>

            <div class="no-comments" v-if="!commentsLoading && comments.length === 0">
              <div class="empty-state">
                <i class="el-icon-chat-dot-round empty-icon"></i>
                <p class="empty-text">暂无评论</p>
                <p class="empty-subtext">成为第一个评论的人吧</p>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 评论对话框 -->
    <el-dialog 
      :title="commentDialogTitle" 
      :visible.sync="showCommentDialog"
      width="500px"
    >
      <el-form :model="commentForm" ref="commentForm" :rules="commentRules">
        <el-form-item label="评论内容" prop="commentcontent">
          <el-input 
            v-model="commentForm.commentcontent" 
            type="textarea" 
            :rows="4"
            placeholder="请输入您的评论..."
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showCommentDialog = false">取消</el-button>
        <el-button type="primary" @click="submitComment">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStoreInfo } from '@/api/store'
import { getDishesByStore, deleteDish } from '@/api/dish'
import { getComments, addComment, updateComment, deleteComment } from '@/api/comment'
import { addToCart } from '@/api/cart'
import { mapGetters } from 'vuex'

export default {
  name: 'StoreDetail',
  data() {
    return {
      storeId: null,
      store: null,
      dishes: [],
      comments: [],
      activeTab: 'dishes',
      storeLoading: false,
      dishesLoading: false,
      commentsLoading: false,
      showCommentDialog: false,
      commentForm: {
        commentcontent: '',
        storeid: null
      },
      commentRules: {
        commentcontent: [
          { required: true, message: '请输入评论内容', trigger: 'blur' }
        ]
      },
      editingComment: null
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn', 'userInfo']),
    
    isStoreOwner() {
      return this.store && this.userInfo && this.store.userid === this.userInfo.userid
    },
    
    commentDialogTitle() {
      return this.editingComment ? '编辑评论' : '发表评论'
    }
  },
  methods: {
    async loadStoreInfo() {
      this.storeLoading = true
      try {
        const response = await getStoreInfo(this.storeId)
        this.store = response.data.data
      } catch (error) {
        this.$message.error('获取商店信息失败：' + error.message)
      } finally {
        this.storeLoading = false
      }
    },
    
    async loadDishes() {
      this.dishesLoading = true
      try {
        const response = await getDishesByStore({ storeid: this.storeId })
        this.dishes = response.data.data.list || []
      } catch (error) {
        this.$message.error('获取菜品列表失败：' + error.message)
      } finally {
        this.dishesLoading = false
      }
    },
    
    async loadComments() {
      this.commentsLoading = true
      try {
        const response = await getComments(this.storeId)
        this.comments = response.data.data || []
      } catch (error) {
        this.$message.error('获取评论失败：' + error.message)
      } finally {
        this.commentsLoading = false
      }
    },
    
    async addToCart(dish) {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      try {
        await addToCart(dish.dishname, dish.dishprice, this.userInfo.userid)
        this.$message.success('已添加到购物车')
      } catch (error) {
        this.$message.error('添加失败：' + error.message)
      }
    },
    
    editStore() {
      this.$router.push(`/store-management/info`)
    },
    
    addDish() {
      this.$router.push(`/store-management/dishes`)
    },
    
    editDish(dish) {
      this.$router.push(`/store-management/dishes?edit=${dish.dishid}`)
    },
    
    async deleteDish(dishId) {
      try {
        await this.$confirm('确定要删除这个菜品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await deleteDish(dishId)
        this.$message.success('删除成功')
        this.loadDishes()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + error.message)
        }
      }
    },
    
    editComment(comment) {
      this.editingComment = comment
      this.commentForm.commentcontent = comment.commentcontent
      this.showCommentDialog = true
    },
    
    async deleteComment(commentId) {
      try {
        await this.$confirm('确定要删除这条评论吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await deleteComment(commentId)
        this.$message.success('删除成功')
        this.loadComments()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + error.message)
        }
      }
    },
    
    async submitComment() {
      try {
        await this.$refs.commentForm.validate()
        
        if (this.editingComment) {
          await updateComment(this.commentForm.commentcontent, this.editingComment.commentid)
          this.$message.success('评论更新成功')
        } else {
          await addComment({
            commentcontent: this.commentForm.commentcontent,
            storeid: this.storeId
          })
          this.$message.success('评论发表成功')
        }
        
        this.showCommentDialog = false
        this.resetCommentForm()
        this.loadComments()
      } catch (error) {
        this.$message.error('操作失败：' + error.message)
      }
    },
    
    resetCommentForm() {
      this.commentForm.commentcontent = ''
      this.editingComment = null
      this.$refs.commentForm.resetFields()
    },
    
    canEditComment(comment) {
      return this.isLoggedIn
    },
    
    formatTime(commentId) {
      // 简单的格式化，实际项目中应该使用真实的时间戳
      return new Date().toLocaleString()
    }
  },
  
  mounted() {
    this.storeId = parseInt(this.$route.params.id)
    this.loadStoreInfo()
    this.loadDishes()
    this.loadComments()
  }
}
</script>

<style lang="scss" scoped>
.store-detail-container {
  padding: 20px;
  
  .store-header {
    margin-bottom: 30px;
    
    .store-info {
      display: flex;
      gap: 20px;
      
      .store-image {
        width: 200px;
        height: 150px;
        overflow: hidden;
        border-radius: 8px;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .store-details {
        flex: 1;
        
        .store-name {
          margin: 0 0 10px 0;
          font-size: 24px;
          color: #333;
        }
        
        .store-description {
          margin: 0 0 20px 0;
          color: #666;
          line-height: 1.6;
        }
      }
    }
  }
  
  .store-content {
    .dishes-section, .comments-section {
      .dishes-header, .comments-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        
        h3 {
          margin: 0;
          font-size: 18px;
          color: #333;
        }
      }
    }
    
    .dish-card {
      margin-bottom: 20px;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-5px);
      }
      
      .dish-image {
        height: 150px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .dish-info {
        padding: 15px 0;
        
        .dish-name {
          margin: 0 0 10px 0;
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }
        
        .dish-description {
          margin: 0 0 10px 0;
          color: #666;
          font-size: 14px;
          line-height: 1.4;
          height: 40px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .dish-price {
          font-size: 16px;
          font-weight: bold;
          color: #e74c3c;
          margin-bottom: 15px;
        }
        
        .dish-actions {
          .owner-actions {
            display: flex;
            gap: 10px;
          }
        }
      }
    }
    
    .comments-list {
      .comment-item {
        border-bottom: 1px solid #eee;
        padding: 15px 0;
        
        .comment-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          
          .comment-user {
            font-weight: bold;
            color: #333;
          }
          
          .comment-time {
            color: #999;
            font-size: 12px;
          }
        }
        
        .comment-content {
          color: #666;
          line-height: 1.6;
          margin-bottom: 10px;
        }
        
        .comment-actions {
          text-align: right;
        }
      }
    }
  }
  
  .no-dishes, .no-comments {
    text-align: center;
    margin-top: 50px;
    
    .empty-state {
      .empty-icon {
        font-size: 64px;
        color: #ddd;
        margin-bottom: 20px;
      }
      
      .empty-text {
        font-size: 18px;
        color: #666;
        margin-bottom: 10px;
      }
      
      .empty-subtext {
        font-size: 14px;
        color: #999;
      }
    }
  }
}
</style> 